﻿using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;

namespace EpisodeWizard.Core
{

    public class PluginManager<T>
    {

		/// <summary>
		/// Stores plugin instances
		/// Some of which are active and some inactive
		/// </summary>
		public class PluginInstance
		{
			public PluginInstance(T _Instance)
			{
				Instance = _Instance;
				Active = false;
			}
			public T Instance;
			public bool Active;
		}

		/// <summary>
		/// Looks in a specific folder for plugins that match the template interface
		/// Returns a list that contains one instance of each plugin found
		/// </summary>
        public static List<PluginInstance> GetPlugins(string FullPath)
		{
			//Debug.Assert(typeof(T).IsInterface, "This function must be called to find plugins matching a given interface");

			List<PluginInstance> tList = new List<PluginInstance>();
            string[] files = null;

            try
            {
                files = Directory.GetFiles(FullPath, "*.dll");
            }
            catch (DirectoryNotFoundException)
            {
                return tList;
            }
            
			foreach (string file in files) 
			{
				try 
				{
					Assembly assembly = Assembly.LoadFile(file);
					foreach (Type type in assembly.GetTypes()) 
					{
						if (!type.IsClass || type.IsNotPublic)
						{
							continue;
						}
												
						if (typeof(T).IsAssignableFrom(type))
						{
							object obj = Activator.CreateInstance(type);
							T Instance = (T)obj;
							tList.Add(new PluginInstance(Instance));
						}
					} 
				}
				catch (Exception ex)
				{
					Debug.WriteLine(ex.Message);
				}
			}
			return tList; 
		}
	
	
	}

}


